/*
Copyright (C) 2015 Jochem Raat

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/* Commentary:

This file implements markov chains as a means of constructing
believable names for islands. This is done by means of first
constructing a representation of the chains in the form of a map,
which maps N characters to the frequency in which it occured and a
list of possible following characters and their frequencies.
*/

#include <markovNames.h>

#include <fstream>
#include <iostream>
#include <algorithm>
#include <stdexcept>

MarkovNames::MarkovNames(std::string trainingFileName,
                         int groupSize,
                         std::mt19937 *mt)
{
    this->trainingFileName = trainingFileName;
    this->groupSize = groupSize;
    this->mt = mt;

    this->markovData.beginnings.frequency = 0;

    this->maxWords = 6;
    this->maxWordLength = 30;

    train();
}

std::vector<std::string> MarkovNames::getTrainingNames()
{
    std::ifstream file(this->trainingFileName);
    std::string line;
    std::vector<std::string> names;

    if (!file) {
        std::cerr << "Error on reading name training file: "
                  << this->trainingFileName << std::endl;
        throw std::invalid_argument("File couldn't be read");
    }

    while (!file.eof()) {
        getline(file, line);
        names.push_back(line);
    }
    file.close();

    return names;
}

void MarkovNames::train()
{
    std::vector<std::string> names = getTrainingNames();

    for (auto name : names) {
        trainName(name);
    }
}

void MarkovNames::trainName(std::string name)
{
    // Add the beginning `groupSize` characters of the name to the
    // beginnings.
    std::string begin = name.substr(0, this->groupSize);
    char next;

    ++(this->markovData.beginnings.frequency);
    if (this->markovData.beginnings.possibilities.find(begin)
        != this->markovData.beginnings.possibilities.end())
        ++(this->markovData.beginnings.possibilities[begin]);
    else
        this->markovData.beginnings.possibilities[begin] = 1;

    for (;name.length() >= this->groupSize; name.erase(0, 1)) {
        begin = name.substr(0, this->groupSize);

        next = '\n';
        if (name.length() > this->groupSize)
            next = name.at(this->groupSize);
        addToMarkovMap(&(this->markovData.markovMap), begin, next);
    }
}

void MarkovNames::addToMarkovMap(MarkovMap *map,
                                 std::string current,
                                 char next)
{
    MarkovElement element;
    MarkovElement &rElement = element;

    if (map->find(current) != map->end()) { // current is in map
        rElement = map->at(current);
    } else {
        rElement.frequency = 0;
    }

    ++element.frequency;
    addToPossibilities(&(element.possibilities), next);
    (*map)[current] = element;
}

void MarkovNames::addToPossibilities(std::map<char, int> *possibilities,
                                     char next)
{
    if (possibilities->find(next) != possibilities->end()) {
        int &freq = possibilities->at(next);
        ++freq;
    } else
        (*possibilities)[next] = 1;
}

std::string MarkovNames::createName()
{
    std::string name;
    bool good;

    std::normal_distribution<double> distribution(1.0,0.2);
    double rand = distribution(*(this->mt));
    rand = std::max(rand, 0.0);

    while (!good) {
        name = getName();

        int words = 0,
            longestWord = 0,
            currentWord = 0,
            nameLength = 0;

        for (auto c : name) {
            ++nameLength;
            if (c == ' ') {
                ++words;
                longestWord = std::max(currentWord, longestWord);
                currentWord = 0;
            } else
                ++currentWord;

        }
        good = (words < this->maxWords)
            && (longestWord < this->maxWordLength)
            && (nameLength * rand > 5)
            && (nameLength * rand < 30);
    }

    return name;
}

std::string MarkovNames::getName()
{
    std::string name = chooseBeginning();
    char next;

    while (name.length() >= this->groupSize
           && (next = chooseNext(name.substr(name.length()
                                          - this->groupSize)))
           != '\n') {

        name.push_back(next);
    }
    return name;
}

std::string MarkovNames::chooseBeginning()
{
    std::uniform_int_distribution<int>
        dist(1, this->markovData.beginnings.frequency);
    int n = dist(*(this->mt));

    for (auto begin : this->markovData.beginnings.possibilities) {
        n -= begin.second;
        if (n < 1)
            return begin.first;
    }

}

char MarkovNames::chooseNext(std::string current)
{
    std::uniform_int_distribution<int>
        dist(1, this->markovData.markovMap[current].frequency);
    int n = dist(*(this->mt));

    for (auto pos :
             this->markovData.markovMap[current].possibilities) {
        n -= pos.second;
        if (n < 1)
            return pos.first;
    }
}
